package com.CuandoLlegaAndroid;

import java.util.ArrayList;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class SortFavouritesPreferences extends PreferenceActivity {
	
	ArrayList<String> keys = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.sort_favouritespreferences);

		keys = new ArrayList<String>();

		keys.add("sortLine");
		keys.add("sortDescrip");
		keys.add("sortDate");
		keys.add("sortNro");
		keys.add("sortStreet");
		keys.add("sortInters");

		for (int i = 0; i < keys.size(); i++) {

			Preference p = (Preference) findPreference(keys.get(i));
			p.setOnPreferenceClickListener(new OnPreferenceClickListener() {

				public boolean onPreferenceClick(Preference preference) {
					SetSortPreferences(preference);
					finish();
					return true;

				}
			});
		}
	}

	private void SetSortPreferences(Preference preference) {
		String key = preference.getKey();

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());

		int value = prefs.getInt(key, 0);

		SharedPreferences.Editor editor = prefs.edit();

		if (value == 0 || value == 2) {
			editor.putInt(key, 1);
		} else {
			editor.putInt(key, 2);
		}


		
		for (int i = 0; i < keys.size(); i++) 
		{
			String otherKey = keys.get(i);
			if(!key.equals(otherKey))
			{
				editor.putInt(otherKey, 0);
			}
		}
		
		editor.commit();
	}

}